package io.mvvm.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: Netty
 * @description: BIO 服务端
 * @author: 潘
 * @create: 2021-01-17 19:03
 **/
public class BioServer {

    public static void main(String[] args) throws Exception {
        // 创建一个线程池, 如果有客户端连接就创建一个线程进行通讯
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();

        // 创建 ServerSocket
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务端启动...");

        while (true) {
            System.out.println("Thread ID：" + Thread.currentThread().getId() +
                    " Thread Name：" + Thread.currentThread().getName());
            // 监听，等待客户端连接
            System.out.println("等待客户端连接");
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");

            // 创建一个线程进行通讯
            newCachedThreadPool.execute(() -> {
                handler(socket);
            });
        }
    }

    private static void handler(Socket socket) {
        try {
            System.out.println("Thread ID：" + Thread.currentThread().getId() +
                    " Thread Name：" + Thread.currentThread().getName());
            byte[] bytes = new byte[1024];
            // 通过 Socket 获取输入流
            InputStream inputStream = socket.getInputStream();

            // 循环读取客户端发送的数据
            while (true) {
                System.out.println("Thread ID：" + Thread.currentThread().getId() +
                        " Thread Name：" + Thread.currentThread().getName());

                System.out.println("读取数据...");
                int read = inputStream.read(bytes);
                if (read != -1) {
                    System.out.println(new String(bytes, 0, read));
                } else {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
